package com.scrm.server.wx.cp.service.impl;

import com.scrm.common.dto.BatchDTO;
import com.scrm.common.util.ListUtils;
import com.scrm.server.wx.cp.dto.*;
import com.scrm.server.wx.cp.entity.BrSopDetail;
import com.scrm.server.wx.cp.entity.BrTodo;
import com.scrm.server.wx.cp.service.IBrSopDetailService;
import com.scrm.server.wx.cp.service.IBrTodoService;
import com.scrm.server.wx.cp.service.IXxlJobService;
import lombok.extern.slf4j.Slf4j;
import com.scrm.server.wx.cp.entity.BrSopRule;
import com.scrm.server.wx.cp.mapper.BrSopRuleMapper;
import com.scrm.server.wx.cp.service.IBrSopRuleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.scrm.server.wx.cp.vo.BrSopRuleVO;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import com.scrm.common.util.UUID;
import com.scrm.common.exception.BaseException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import java.util.stream.Collectors;

/**
 * sop规则 服务实现类
 * @author ouyang
 * @since 2022-04-17
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class BrSopRuleServiceImpl extends ServiceImpl<BrSopRuleMapper, BrSopRule> implements IBrSopRuleService {

    @Autowired
    private IBrSopDetailService detailService;

    @Autowired
    private IXxlJobService xxlJobService;

    @Autowired
    private IBrTodoService todoService;

    @Override
    public List<BrSopRuleVO> queryList(BrSopRuleQueryDTO dto){
        LambdaQueryWrapper<BrSopRule> wrapper = new QueryWrapper<BrSopRule>()
        .lambda().eq(BrSopRule::getExtCorpId, dto.getExtCorpId())
                .eq(BrSopRule::getSopId,dto.getSopId())
                .orderByAsc(BrSopRule::getCreatedAt);
        return Optional.ofNullable(list(wrapper)).orElse(new ArrayList<>()).stream().map(this::translation).collect(Collectors.toList());
    }


    @Override
    public BrSopRuleVO findById(String id){
        return translation(checkExists(id));
    }


    @Override
    public BrSopRule save(BrSopRuleSaveOrUpdateDTO dto){

        //封装数据
        BrSopRule brSopRule = new BrSopRule();
        BeanUtils.copyProperties(dto,brSopRule);

        brSopRule.setId(UUID.get32UUID())
                .setCreatedAt(new Date());
        //入库
        save(brSopRule);

        return brSopRule;
    }


    @Override
    public BrSopRule update(BrSopRuleSaveOrUpdateDTO dto){

        //校验参数
        BrSopRule old = checkExists(dto.getId());
        //封装数据
        BeanUtils.copyProperties(dto, old,"creator");
        old.setUpdatedAt(new Date());
        //入库
        updateById(old);

        return old;
    }


    @Override
    public void deleteBySopId(String sopId){
        List<BrSopRule> ruleList = list(new LambdaQueryWrapper<BrSopRule>().eq(BrSopRule::getSopId, sopId)).stream().collect(Collectors.toList());
        if (ListUtils.isEmpty(ruleList)){
            return;
        }
        List<String> ruleIdList = ruleList.stream().map(e -> e.getId()).collect(Collectors.toList());
        batchDelete(new BatchDTO<String>().setIds(ruleIdList));
    }


    @Override
    public void batchDelete(BatchDTO<String> dto){

        //校验参数
        List<BrSopRule> ruleList = new ArrayList<>();
        Optional.ofNullable(dto.getIds()).orElse(new ArrayList<>()).forEach(id -> ruleList.add(checkExists(id)));

        //删除
        removeByIds(dto.getIds());

        //删除detail关联
        detailService.remove(new LambdaQueryWrapper<BrSopDetail>().in(BrSopDetail::getRuleId, dto.getIds()));

        //删除待办
        todoService.remove(new LambdaQueryWrapper<BrTodo>().in(BrTodo::getBusinessId,dto.getIds()).eq(BrTodo::getType,BrTodo.SOP_TYPE));

        //删除定时任务
        List<Integer> jobIds = new ArrayList<>();
        ruleList.stream().forEach(rule->{
                    if (ListUtils.isNotEmpty(rule.getJobId())){
                        jobIds.addAll(rule.getJobId());
                    }
                }
        );
        if (ListUtils.isNotEmpty(jobIds)){
            jobIds.forEach(jobId->{
                xxlJobService.delete(jobId);
            });
        }

    }


    /**
     * 翻译
     * @param brSopRule 实体
     * @return BrSopRuleVO 结果集
     * @author ouyang
     * @date 2022-04-17
     */
    private BrSopRuleVO translation(BrSopRule brSopRule){
        BrSopRuleVO vo = new BrSopRuleVO();
        BeanUtils.copyProperties(brSopRule, vo);
        return vo;
    }


    @Override
    public BrSopRule checkExists(String id){
        if (StringUtils.isBlank(id)) {
            return null;
        }
        BrSopRule byId = getById(id);
        if (byId == null) {
            throw new BaseException("sop规则不存在");
        }
        return byId;
    }
}
